package controllers;

import hardwarelvl.ScheduleStorage;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;

import org.kxml2.io.KXmlParser;
import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import commands.*;
import core.ScheduleEntry;

public class StorageController implements CommandListener{
	
	private Hashtable m_records;
	private ScheduleStorage m_storage;
	
	public StorageController(){
		m_records = new Hashtable();
		m_storage = new ScheduleStorage();
		Dispatcher.getInstance().registerListener(this, Commands.NewEntry);
		Dispatcher.getInstance().registerListener(this, Commands.Start);
		Dispatcher.getInstance().registerListener(this, Commands.RemoveEntry);
	}

	public void commandAction(Command cmd, Displayable arg1) {
		switch(cmd.getCommandType()){
		case Command.ITEM:
			if (cmd.getLabel().equals(Commands.Start)){
				try {
					m_storage.open();
					Hashtable records = m_storage.readAll();
					Enumeration keys  = records.keys();
					while ( keys.hasMoreElements() ){
						Integer key = ((Integer)keys.nextElement());
						String xml = (String)records.get(key);
						loadEntryFromRecord(key.intValue(), xml);
					}
						
				} 
				catch (Throwable e) {
				}
			}
			if (cmd.getLabel().equals(Commands.NewEntry)){
				NewEntryCommand newCmd = (NewEntryCommand)cmd;
				saveEntry(newCmd.getEntry());
			}
			if (cmd.getLabel().equals(Commands.RemoveEntry)){
				RemoveEntryCommand removeCmd = (RemoveEntryCommand)cmd;
				deleteEntry(removeCmd.getEntry());
			}
			break;
		}
	}
	
	private void loadEntryFromRecord(int recordId, String xml) throws Throwable{
		
		XmlPullParser parser = new KXmlParser();
		InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xml.getBytes()));
		parser.setInput(reader);
		Document readDoc = new Document();
		readDoc.parse(parser);
		
		ScheduleEntry newEntry = ScheduleEntry.fromXml(readDoc.getRootElement());
		m_records.put(new Integer(recordId), newEntry);
		Dispatcher.getInstance().handleCommand(new LoadEntryCommand(newEntry));
	}

	public void saveEntry(ScheduleEntry entry){
		try {
			ByteArrayOutputStream byteArrOutStream = new ByteArrayOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(byteArrOutStream );
	        Document doc = new Document();
			
			entry.toXml(doc);
	        XmlSerializer serializer = new KXmlSerializer();
	        serializer.setOutput(writer);
	        doc.write(serializer);
	        
	        int newId = m_storage.saveEntry(byteArrOutStream.toString());
	        m_records.put(new Integer(newId), entry);			
		} catch (Throwable e) {
			e.printStackTrace();
		}		
	}
	
	public void deleteEntry(ScheduleEntry entry){
			
	}
}
